<template>
  <el-container style="height: 600px; border: 1px solid #eee">
    <!-- 增加资源的弹出框 -->
    <el-dialog title="新增商品类型" :visible.sync="addFormVisible">
      <!-- 商品名称 -->
      <el-form ref="addForm" :model="addForm" :rules="rules">
        <el-form-item
          :label="tableFomat[1].label"
          :label-width="formLabelWidth"
          style="display:inline-block"
          prop="goods_name"
        >
          <el-input v-model="addForm.goods_name" autocomplete="off" placeholder="请输入商品名称" />
        </el-form-item>
        <!-- 商品详情图 -->
        <el-form-item
          label="商品详情图"
          :label-width="formLabelWidth"
          style="display:inline-block"
          prop="detail_images_url"
        >
          <el-upload
            ref="upload"
            action
            list-type="picture-card"
            :http-request="uploadFile"
            :on-preview="handlePictureCardPreview"
            :on-remove="(file,fileList) => deleteFile(file,fileList,'addForm.detail_images_url')"
            :before-remove="beforeRemove"
            :multiple="true"
            :limit="10"
            :on-exceed="handleExceedMore"
            accept=".JPG, .PNG, .SVG, .WEBP, .GIF"
            :data="{name: 'addForm.detail_images_url'}"
          >
            <i class="el-icon-plus" />
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt>
          </el-dialog>
        </el-form-item>
        <!-- 商品详情描述 -->
        <el-form-item
          :label="tableFomat[2].label"
          :label-width="formLabelWidth"
          style="display:inline-block"
          prop="detail"
        >
          <el-input v-model="addForm.detail" type="textarea" />
        </el-form-item>
        <br>
        <!-- 商品简短描述 -->
        <el-form-item
          :label="tableFomat[3].label"
          :label-width="formLabelWidth"
          style="display:inline-block"
          prop="goods_brief"
        >
          <el-input
            v-model="addForm.goods_brief"
            type="textarea"
            autocomplete="off"
            placeholder="商品售卖是的标题"
          />
        </el-form-item>
        <!-- 商品关键字 -->
        <el-form-item
          :label="tableFomat[4].label"
          :label-width="formLabelWidth"
          style="display:inline-block"
          prop="key_words"
        >
          <el-input v-model="addForm.key_words" autocomplete="off" />
        </el-form-item>

        <!-- 商品最低价格 -->
        <el-form-item
          label="商品最低价格"
          :label-width="formLabelWidth"
          style="display:inline-block"
          prop="low_price"
        >
          <el-input v-model="addForm.low_price" autocomplete="off" type="number" />
        </el-form-item>

        <!-- 商品主图 -->
        <el-form-item
          label="商品主图"
          :label-width="formLabelWidth"
          style="display:inline-block"
          prop="main_image_url"
        >
          <el-upload
            ref="upload1"
            action
            list-type="picture-card"
            :http-request="uploadFile"
            :on-preview="handlePictureCardPreview"
            :on-remove="(file,fileList) => deleteFile(file,fileList,'addForm.main_image_url')"
            :limit="1"
            :on-exceed="handleExceed"
            :before-remove="beforeRemove"
            accept=".JPG, .PNG, .SVG, .WEBP, .GIF"
            :data="{name: 'addForm.main_image_url'}"
          >
            <i class="el-icon-plus" />
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt>
          </el-dialog>
        </el-form-item>
        <!-- 商品附属图 -->
        <el-form-item
          label="商品附属图"
          :label-width="formLabelWidth"
          style="display:inline-block"
          prop="secondary_images_url"
        >
          <el-upload
            ref="upload2"
            action
            list-type="picture-card"
            :http-request="uploadFile"
            :on-preview="handlePictureCardPreview"
            :on-remove="(file,fileList) => deleteFile(file,fileList,'addForm.secondary_images_url')"
            :multiple="true"
            :limit="10"
            :on-exceed="handleExceedMore"
            :before-remove="beforeRemove"
            accept=".JPG, .PNG, .SVG, .WEBP, .GIF"
            :data="{name: 'addForm.secondary_images_url'}"
          >
            <i class="el-icon-plus" />
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt>
          </el-dialog>
        </el-form-item>
        <!-- 商品分类 -->
        <el-form-item
          :label="tableFomat[6].label"
          :label-width="formLabelWidth"
          style="display:inline-block"
          prop="type_id"
        >
          <div class="block">
            <el-cascader
              :props="props"
              filterable
              @change="(value) => handlechange(value,'addForm.type_id')"
            />
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addGoods('addForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑资源的弹出框 -->
    <el-dialog title="修改商品类型" :visible.sync="updateFormVisible">
      <el-form ref="updateForm" :model="updateForm" :rules="rules">
        <el-form-item
          :label="tableFomat[1].label"
          :label-width="formLabelWidth"
          style="display:inline-block"
          prop="goods_name"
        >
          <el-input v-model="updateForm.goods_name" autocomplete="off" placeholder="请输入商品名称" />
        </el-form-item>
        <!-- 商品详情图 -->
        <el-form-item
          label="商品详情图"
          :label-width="formLabelWidth"
          style="display:inline-block"
          prop="detail_images_url"
        >
          <el-upload
            action
            list-type="picture-card"
            :http-request="uploadFile"
            :on-preview="handlePictureCardPreview"
            :on-remove="(file,fileList) => deleteFile(file,fileList,'updateForm.detail_images_url')"
            :before-remove="beforeRemove"
            :multiple="true"
            :limit="10"
            :on-exceed="handleExceedMore"
            :file-list="detail_images_url"
            accept=".JPG, .PNG, .SVG, .WEBP, .GIF"
            :data="{name: 'updateForm.detail_images_url'}"
          >
            <i class="el-icon-plus" />
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt>
          </el-dialog>
        </el-form-item>
        <!-- 商品详情描述 -->
        <el-form-item
          :label="tableFomat[2].label"
          :label-width="formLabelWidth"
          style="display:inline-block"
          prop="detail"
        >
          <el-input v-model="updateForm.detail" type="textarea" />
        </el-form-item>
        <br>
        <!-- 商品简短描述 -->
        <el-form-item
          :label="tableFomat[3].label"
          :label-width="formLabelWidth"
          style="display:inline-block"
          prop="goods_brief"
        >
          <el-input
            v-model="updateForm.goods_brief"
            type="textarea"
            autocomplete="off"
            placeholder="商品售卖是的标题"
          />
        </el-form-item>
        <!-- 商品关键字 -->
        <el-form-item
          :label="tableFomat[4].label"
          :label-width="formLabelWidth"
          style="display:inline-block"
          prop="key_words"
        >
          <el-input v-model="updateForm.key_words" autocomplete="off" />
        </el-form-item>

        <!-- 商品最低价格 -->
        <el-form-item
          label="商品最低价格"
          :label-width="formLabelWidth"
          style="display:inline-block"
          prop="low_price"
        >
          <el-input v-model="updateForm.low_price" autocomplete="off" type="number" />
        </el-form-item>

        <!-- 商品主图 -->
        <el-form-item
          label="商品主图"
          :label-width="formLabelWidth"
          style="display:inline-block"
          prop="main_image_url"
        >
          <el-upload
            action
            list-type="picture-card"
            :http-request="uploadFile"
            :on-preview="handlePictureCardPreview"
            :on-remove="(file,fileList) => deleteFile(file,fileList,'updateForm.main_image_url')"
            :limit="1"
            :on-exceed="handleExceed"
            :before-remove="beforeRemove"
            accept=".JPG, .PNG, .SVG, .WEBP, .GIF"
            :file-list="main_image_url"
            :data="{name: 'updateForm.main_image_url'}"
          >
            <i class="el-icon-plus" />
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt>
          </el-dialog>
        </el-form-item>
        <!-- 商品附属图 -->
        <el-form-item
          label="商品附属图"
          :label-width="formLabelWidth"
          style="display:inline-block"
          prop="secondary_images_url"
        >
          <el-upload
            action
            list-type="picture-card"
            :http-request="uploadFile"
            :on-preview="handlePictureCardPreview"
            :on-remove="(file,fileList) => deleteFile(file,fileList,'updateForm.secondary_images_url')"
            :multiple="true"
            :limit="10"
            :on-exceed="handleExceedMore"
            :before-remove="beforeRemove"
            accept=".JPG, .PNG, .SVG, .WEBP, .GIF"
            :file-list="secondary_images_url"
            :data="{name: 'updateForm.secondary_images_url'}"
          >
            <i class="el-icon-plus" />
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt>
          </el-dialog>
        </el-form-item>
        <!-- 商品分类 -->
        <el-form-item
          :label="tableFomat[6].label"
          :label-width="formLabelWidth"
          style="display:inline-block"
          prop="type_id"
        >
          <div class="block">
            <el-cascader
              :props="props"
              :value="updateForm.type_id"
              filterable
              @change="(value) => handlechange(value,'updateForm.type_id')"
            />
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateGoods('updateForm')">确 定</el-button>
      </div>
    </el-dialog>
    <el-container>
      <!-- 搜索区 -->
      <el-header>
        <el-input v-model="search.code" placeholder="商品编号" style="width:300px;" />
        <el-input v-model="search.name" placeholder="商品名称" style="width:300px;" />
        <el-button type="primary" icon="el-icon-search" @click="searchGoods()">搜索</el-button>
      </el-header>

      <!-- 功能区 -->
      <el-main style="height:600px;">
        <el-row>
          <el-button type="success" size="mini" @click="add()">增加</el-button>
          <el-button type="primary" size="mini" @click="Edit()">编辑</el-button>
          <el-button size="mini" type="danger" @click="deletes()">删除</el-button>
        </el-row>
        <!-- 表格 组件 -->
        <datatable
          :table-fomat="tableFomat"
          :table-data="tableData"
          :total="tableData.length"
          @handleEdit="handleEdit"
          @handleDelete="handleDelete"
          @handleSelectionChange="handleSelectionChange"
        >
          <el-table-column label="商品详情图" width="300">
            <template slot-scope="scope">
              <!-- <div style="display:inline; margin:0px 5px" v-for="item in scope.row" :key="item._id"> -->
              <el-avatar
                v-for="fit in scope.row.detail_images_url"
                :key="fit"
                style="margin: 0px 2px"
                shape="square"
                :size="50"
                :src="fit"
              >
                <!-- 加载失败时显示 -->
                <img :src="imgUrl">
              </el-avatar>
              <!-- </div> -->
            </template>
          </el-table-column>
          <el-table-column label="商品主图" width="100">
            <template slot-scope="scope">
              <el-avatar
                v-for="fit in scope.row.goods_image.main_image_url"
                :key="fit"
                style="margin: 0px 2px"
                shape="square"
                :size="50"
                :src="fit"
              >
                <img :src="imgUrl">
              </el-avatar>
            </template>
          </el-table-column>
          <el-table-column label="商品附属图" width="300">
            <template slot-scope="scope">
              <el-avatar
                v-for="fit in scope.row.goods_image.secondary_images_url"
                :key="fit"
                style="margin: 0px 2px"
                shape="square"
                :size="50"
                :src="fit"
              >
                <img :src="imgUrl">
              </el-avatar>
            </template>
          </el-table-column>
        </datatable>
      </el-main>
    </el-container>
  </el-container>
</template>
<style>
/* 容器头部 和  */
.el-header {
  line-height: 60px;
}
.el-aside {
  width: 200px !important;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  color: #333;
  background-color: white;
}
</style>
<script>
import datatable from '@/views/my-views/components/table'
import goods from '@/sql/table-field/index'
import { tsFormatTime } from '@/tools/util'
import { mapGetters } from 'vuex'
import FlakeId from 'flake-idgen'
import informat from 'biguint-format'
// 使用雪花算法生成商品的编号
var flakeIdGen = new FlakeId()
export default {
  name: 'GoodsList',
  components: {
    datatable
  },
  data() {
    return {
      // 表单认证规则
      rules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { max: 10, message: '长度在不能大于 10 个字符', trigger: 'blur' }
        ],
        detail_images_url: [
          { required: true, message: '请选择商品详情图', trigger: 'change' }
        ],
        detail: [
          { required: true, message: '请输入商品详情介绍', trigger: 'blur' },
          { max: 100, message: '长度在不能大于 100 个字符', trigger: 'blur' }
        ],
        goods_brief: [
          { required: true, message: '请输入商品简短描述', trigger: 'blur' },
          { max: 80, message: '长度在不能大于 50 个字符', trigger: 'blur' }
        ],
        key_words: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { max: 10, message: '长度在不能大于 10 个字符', trigger: 'blur' }
        ],
        low_price: [
          { required: true, message: '请输入商品最低价格', trigger: 'blur' }
        ],
        main_image_url: [
          { required: true, message: '请选择商品主图', trigger: 'change' }
        ],
        secondary_images_url: [
          { required: true, message: '请选择商品附属图', trigger: 'change' }
        ],
        type_id: [
          { required: true, message: '请选择商品类型', trigger: 'change' }
        ]
      },
      // 用于图片回显
      secondary_images_url: [],
      main_image_url: [],
      detail_images_url: [],
      // 图片加载失败时显示的图片
      imgUrl:
        'https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png',
      // 用于商品分类的动态加载
      props: {},
      // 文件上传是放大图片
      dialogImageUrl: '',
      dialogVisible: false,
      // 解决notice通知栏覆盖问题
      notifyPromise: Promise.resolve(),
      // 搜索输入框的值
      search: {
        code: '',
        name: ''
      },
      // 表格显示格式(列名以及列对应显示的数据)
      tableFomat: goods.goods,
      // 表格数据
      tableData: [],
      // 当前表格选中的数据
      multipleSelection: [],

      // 增加的弹出框设置
      addFormVisible: false,
      addForm: {
        // 商品编号
        goods_no: '',
        // 商品的类型id
        type_id: '',
        // 商品的名字
        goods_name: '',
        // 商品的详情图url
        detail_images_url: [],
        // 商品的详情介绍
        detail: '',
        // 商品的简短描述
        goods_brief: '',
        // 商品的关键字
        key_words: '',
        low_price: 0,
        // 商品的主图url
        main_image_url: [],
        // 商品的附属图url
        secondary_images_url: []
      },
      formLabelWidth: '120px',

      // 修改的弹出框设置
      updateFormVisible: false,
      updateForm: {
        _id: '',
        // 商品编号
        goods_no: '',
        // 商品的类型id
        type_id: '',
        // 商品的名字
        goods_name: '',
        // 商品的详情图url
        detail_images_url: [],
        // 商品的详情介绍
        detail: '',
        // 商品的简短描述
        goods_brief: '',
        // 商品的关键字
        key_words: '',
        // 商品最低价格
        low_price: 0,
        // 商品的主图url
        main_image_url: [],
        // 商品的附属图url
        secondary_images_url: []
      }
    }
  },
  computed: {
    // 从store中的getters中获取数据(store/getters.js)
    ...mapGetters(['goodsList'])
  },
  mounted() {
    // 如果state中有数据则从state中读取
    if (this.goodsList.length !== 0) {
      // 使用缓存
      this.tableData = this.goodsList
    } else {
      // 获取商品列表
      this.getGoodsList()
    }
    // 注册商品类型的cascader
    this.registerProps()
  },
  methods: {
    handlechange(value, name) {
      if (name === 'addForm.type_id') {
        this.addForm.type_id = value[value.length - 1]
      } else if (name === 'updateForm.type_id') {
        this.updateForm.type_id = value[value.length - 1]
      }
    },
    // 注册商品类型的cascader ---- bug 没点击之前数据没有加载,所以第一次点击之前没法做数据回显,
    registerProps() {
      this.props = {
        lazy: true,
        lazyLoad: (node, resolve) => {
          const { level } = node
          setTimeout(() => {
            let tableData = []
            this.$store
              .dispatch('getGoodsTypes')
              .then(res => {
                if (res.errcode !== 0) {
                  if (res.errcode === 42001) {
                    this.$notify.error({
                      title: 'Access_token失效,请重新刷登录获取',
                      message: `错误代码:${res.errcode} 错误消息:${res.errmsg}`,
                      duration: 0
                    })
                  } else {
                    this.$notify.error({
                      title: '获取商品类型列表失败',
                      message: `错误代码:${res.errcode} 错误消息:${res.errmsg}`,
                      duration: 0
                    })
                  }
                } else {
                  tableData = JSON.parse(res.resp_data).data.list
                  if (level === 0) {
                    const nodes = tableData
                      .filter(res => res.level === 1)
                      .map(item => ({
                        value: item._id,
                        label: item.type_name,
                        leaf: item.is_has_child === 0
                      }))
                    // 通过调用resolve将子节点数据返回，通知组件数据加载完成
                    resolve(nodes)
                  }
                  if (level === 1) {
                    const nodes = tableData
                      .filter(
                        res => res.level === 2 && res.parent_id === node.value
                      )
                      .map(item => ({
                        value: item._id,
                        label: item.type_name,
                        leaf: item.is_has_child === 0
                      }))
                    // 通过调用resolve将子节点数据返回，通知组件数据加载完成
                    resolve(nodes)
                  }
                  if (level === 2) {
                    const nodes = tableData
                      .filter(
                        res => res.level === 3 && res.parent_id === node.value
                      )
                      .map(item => ({
                        value: item._id,
                        label: item.type_name,
                        leaf: item.is_has_child === 0
                      }))
                    // 通过调用resolve将子节点数据返回，通知组件数据加载完成
                    resolve(nodes)
                  }
                }
              })
              .catch(err => {
                console.log('获取商品的代码逻辑错误', err)
              })
          }, 1000)
        }
      }
    },
    // 上传图片
    uploadFile(param) {
      this.$store
        .dispatch('uploadFile', param.file)
        .then(res => {
          switch (param.data.name) {
            case 'addForm.detail_images_url':
              this.addForm.detail_images_url.push(`http://${res.Location}`)
              break
            case 'addForm.main_image_url':
              this.addForm.main_image_url.push(`http://${res.Location}`)
              break
            case 'addForm.secondary_images_url':
              this.addForm.secondary_images_url.push(`http://${res.Location}`)
              break
            case 'updateForm.detail_images_url':
              this.updateForm.detail_images_url.push(`http://${res.Location}`)
              break
            case 'updateForm.main_image_url':
              this.updateForm.main_image_url.push(`http://${res.Location}`)
              break
            case 'updateForm.secondary_images_url':
              this.updateForm.secondary_images_url.push(
                `http://${res.Location}`
              )
              break
            default:
              alert('没有找到对应的文件上传的url')
              break
          }
          // 上传成功
          param.onSuccess()
        })
        .catch(err => {
          // 上传失败
          param.onError(err)
          console.log(err)
        })
    },
    // 移除图片 ---- bug 当上传同名文件时,移除会所有与改名相同的文件
    deleteFile(file, fileList, name) {
      switch (name) {
        case 'addForm.detail_images_url':
          this.addForm.detail_images_url = this.addForm.detail_images_url.filter(
            res => res.indexOf(file.name) === -1
          )
          break
        case 'addForm.main_image_url':
          this.addForm.main_image_url = this.addForm.main_image_url.filter(
            res => res.indexOf(file.name) === -1
          )
          break
        case 'addForm.secondary_images_url':
          this.addForm.secondary_images_url = this.addForm.secondary_images_url.filter(
            res => res.indexOf(file.name) === -1
          )
          break
        case 'updateForm.detail_images_url':
          this.updateForm.detail_images_url = this.updateForm.detail_images_url.filter(
            res => res.indexOf(file.name) === -1
          )
          break
        case 'updateForm.main_image_url':
          this.updateForm.main_image_url = this.updateForm.main_image_url.filter(
            res => res.indexOf(file.name) === -1
          )
          break
        case 'updateForm.secondary_images_url':
          this.updateForm.secondary_images_url = this.updateForm.secondary_images_url.filter(
            res => res.indexOf(file.name) === -1
          )
          break
        default:
          console.log('not found')
          break
      }
    },
    // 放大图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 超出1个文件数量
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    // 超出10个文件数量
    handleExceedMore(files, fileList) {
      this.$message.warning(
        `当前限制选择 10 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    // 移除文件确认
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    // tip提示方法
    tipformat(res, type, type_name) {
      if (res.errcode !== 0) {
        this.notifyPromise = this.notifyPromise
          .then(this.$nextTick)
          .then(() => {
            this.$notify.error({
              title: `${type}商品失败`,
              message: `错误代码:${res.errcode} 错误消息:${res.errmsg}`,
              duration: 0
            })
          })
      } else {
        this.notifyPromise = this.notifyPromise
          .then(this.$nextTick)
          .then(() => {
            this.$notify({
              title: `${type}商品成功`,
              message: `${type_name}--商品${type}成功`,
              type: 'success',
              duration: 6000
            })
          })
        // 重新从数据库获取数据
        this.getGoodsList()
      }
    },
    // 数据库数据转换为前端显示数据格式
    dataBaseToFormData(value) {
      value.create_time = tsFormatTime(
        value.create_time,
        'Y-M-D h:m:s'
      )
      value.update_time = tsFormatTime(
        value.update_time,
        'Y-M-D h:m:s'
      )
      return value
    },
    // 错误请求消息提示规范
    catchError(type, err) {
      this.$notify.error({
        title: `${type}商品请求失败`,
        message: err,
        duration: 0
      })
    },
    // 添加商品
    addGoods(formName) {
      const type = '添加'
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.addFormVisible = false
          // 使用雪花算法写出十进制的商品编号
          this.addForm.goods_no = informat(flakeIdGen.next(), 'dec')
          this.$store
            .dispatch('addGoods', this.addForm)
            .then(res => {
              // 清空文件列表
              this.$refs.upload.clearFiles()
              this.$refs.upload1.clearFiles()
              this.$refs.upload2.clearFiles()
              // 正常请求消息提示规范
              this.tipformat(res, type, this.addForm.goods_name)
            })
            .catch(err => {
              // 错误请求消息提示
              this.catchError(type, err)
            })
        } else {
          return false
        }
      })
    },
    searchGoods() {
      const type = '搜索'
      this.$store
        .dispatch('searchGoods', this.search)
        .then(res => {
          if (res.errcode !== 0) {
            if (res.errcode === 42001) {
              this.$notify.error({
                title: 'Access_token过期,请重新刷登录获取',
                message: `错误代码:${res.errcode} 错误消息:${res.errmsg}`,
                duration: 0
              })
            } else {
              this.$notify.error({
                title: '获取商品列表失败',
                message: `错误代码:${res.errcode} 错误消息:${res.errmsg}`,
                duration: 0
              })
            }
          } else {
            this.tableData = JSON.parse(res.resp_data).data.list
            this.tableData.map(res => {
              this.dataBaseToFormData(res)
            })
          }
        })
        .catch(err => {
          // 错误请求消息提示
          this.catchError(type, err)
        })
    },
    // 修改商品信息
    updateGoods(formName) {
      const type = '修改'
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.updateFormVisible = false
          this.$store
            .dispatch('updateGoods', this.updateForm)
            .then(res => {
              this.tipformat(res, type, this.updateForm.goods_name)
            })
            .catch(err => {
              this.catchError(type, err)
            })
        } else {
          return false
        }
      })
    },
    // 获取商品列表的方法
    getGoodsList() {
      const type = '获取'
      this.$store
        .dispatch('getGoodsListLinkGoodsType')
        .then(res => {
          if (res.errcode !== 0) {
            if (res.errcode === 42001) {
              this.$notify.error({
                title: 'Access_token过期,请重新刷登录获取',
                message: `错误代码:${res.errcode} 错误消息:${res.errmsg}`,
                duration: 0
              })
            } else {
              this.$notify.error({
                title: '获取商品列表失败',
                message: `错误代码:${res.errcode} 错误消息:${res.errmsg}`,
                duration: 0
              })
            }
          } else {
            this.tableData = JSON.parse(res.resp_data).data.list
            this.tableData.map(res => {
              this.dataBaseToFormData(res)
            })
            this.$store.commit('setGoodsList', this.tableData)
          }
        })
        .catch(err => {
          this.catchError(type, err)
        })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    // 每列的编辑
    handleEdit(index, row) {
      this.updateFormVisible = true
      this.updateForm._id = row._id
      this.updateForm.goods_no = row.goods_no
      this.updateForm.goods_name = row.goods_name
      this.updateForm.detail_images_url = row.detail_images_url
      this.updateForm.detail = row.detail
      this.updateForm.goods_brief = row.goods_brief
      this.updateForm.key_words = row.key_words
      this.updateForm.low_price = row.low_price
      this.updateForm.main_image_url = row.goods_image.main_image_url
      this.updateForm.type_id = row.type_id
      this.updateForm.secondary_images_url =
        row.goods_image.secondary_images_url
      // 用于数据回显
      this.detail_images_url = this.updateForm.detail_images_url.map(res => {
        const arr = res.split('/')
        return {
          name: arr[4],
          url: res
        }
      })
      this.main_image_url = this.updateForm.main_image_url.map(res => {
        const arr = res.split('/')
        return {
          name: arr[4],
          url: res
        }
      })
      this.secondary_images_url = this.updateForm.secondary_images_url.map(
        res => {
          const arr = res.split('/')
          return {
            name: arr[4],
            url: res
          }
        }
      )
    },
    // 每列的删除
    handleDelete(index, row) {
      const type = '删除'
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$store
            .dispatch('deleteGoodsById', row)
            .then(res => {
              this.tipformat(res, type, row.goods_name)
            })
            .catch(err => {
              this.catchError(type, err)
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 头部的添加
    add() {
      this.addFormVisible = true
      // 商品编号
      this.addForm.goods_no = ''
      // 商品的类型id
      this.addForm.type_id = ''
      // 商品的编号
      this.addForm.goods_no = ''
      // 商品的名字
      this.addForm.goods_name = ''
      // 商品的详情图url
      this.addForm.detail_images_url = []
      // 商品的详情介绍
      this.addForm.detail = ''
      // 商品的简短描述
      this.addForm.goods_brief = ''
      // 商品的关键字
      this.addForm.key_words = ''
      // 商品的主图url
      this.addForm.main_image_url = []
      // 商品的附属图url
      this.addForm.secondary_images_url = []
    },
    // 头部的编辑
    Edit() {
      if (this.multipleSelection.length === 1) {
        this.updateFormVisible = true
        this.updateForm._id = this.multipleSelection[0]._id
        this.updateForm.goods_no = this.multipleSelection[0].goods_no
        this.updateForm.goods_name = this.multipleSelection[0].goods_name
        this.updateForm.detail_images_url = this.multipleSelection[0].detail_images_url
        this.updateForm.detail = this.multipleSelection[0].detail
        this.updateForm.goods_brief = this.multipleSelection[0].goods_brief
        this.updateForm.key_words = this.multipleSelection[0].key_words
        this.updateForm.low_price = this.multipleSelection[0].low_price
        this.updateForm.main_image_url = this.multipleSelection[0].goods_image.main_image_url
        this.updateForm.type_id = this.multipleSelection[0].type_id
        this.updateForm.secondary_images_url = this.multipleSelection[0].goods_image.secondary_images_url
        // 用于数据回显
        this.detail_images_url = this.updateForm.detail_images_url.map(res => {
          const arr = res.split('/')
          return {
            name: arr[4],
            url: res
          }
        })
        this.main_image_url = this.updateForm.main_image_url.map(res => {
          const arr = res.split('/')
          return {
            name: arr[4],
            url: res
          }
        })
        this.secondary_images_url = this.updateForm.secondary_images_url.map(
          res => {
            const arr = res.split('/')
            return {
              name: arr[4],
              url: res
            }
          }
        )
      } else {
        this.$message('你有且必须选择一条数据')
      }
    },
    // 头部的删除
    deletes() {
      const type = '删除'
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          if (this.multipleSelection.length >= 1) {
            this.$store
              .dispatch('deleteGoodsByIds', this.multipleSelection)
              .then(res => {
                for (let i = 0; i < this.multipleSelection.length; i++) {
                  this.tipformat(
                    res[i],
                    type,
                    this.multipleSelection[i].goods_name
                  )
                }
              })
              .catch(err => {
                this.catchError(type, err)
              })
          } else {
            this.$notify({
              title: `至少一条数据`,
              type: 'warning'
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }
  }
}
</script>
